import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { VideoTask, VideoTaskList, PaginationParams } from '@/types'
import { request } from '@/api'

export const useVideoStore = defineStore('video', () => {
  // 状态
  const tasks = ref<VideoTask[]>([])
  const currentTask = ref<VideoTask | null>(null)
  const loading = ref(false)
  const total = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(20)

  // 计算属性
  const completedTasks = computed(() =>
    tasks.value.filter(task => task.status === 'completed')
  )

  const processingTasks = computed(() =>
    tasks.value.filter(task => task.status === 'processing')
  )

  const failedTasks = computed(() =>
    tasks.value.filter(task => task.status === 'failed')
  )

  const pendingTasks = computed(() =>
    tasks.value.filter(task => task.status === 'pending')
  )

  // 方法
  const fetchTasks = async (params?: PaginationParams) => {
    loading.value = true
    try {
      const response: VideoTaskList = await request.get('/videos/tasks', {
        page: params?.page || currentPage.value,
        size: params?.size || pageSize.value,
        status: params?.status
      })

      tasks.value = response.tasks
      total.value = response.total
      currentPage.value = response.page

      return response
    } catch (error) {
      console.error('Failed to fetch tasks:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const fetchTask = async (taskId: string) => {
    loading.value = true
    try {
      const task: VideoTask = await request.get(`/videos/tasks/${taskId}`)
      currentTask.value = task

      // 如果任务已在列表中，更新列表中的任务
      const index = tasks.value.findIndex(t => t.id === taskId)
      if (index !== -1) {
        tasks.value[index] = task
      }

      return task
    } catch (error) {
      console.error('Failed to fetch task:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const updateTask = (taskId: string, updates: Partial<VideoTask>) => {
    // 更新当前任务
    if (currentTask.value?.id === taskId) {
      currentTask.value = { ...currentTask.value, ...updates }
    }

    // 更新任务列表中的任务
    const index = tasks.value.findIndex(task => task.id === taskId)
    if (index !== -1) {
      tasks.value[index] = { ...tasks.value[index], ...updates }
    }
  }

  const deleteTask = async (taskId: string) => {
    try {
      await request.delete(`/videos/tasks/${taskId}`)

      // 从列表中移除任务
      const index = tasks.value.findIndex(task => task.id === taskId)
      if (index !== -1) {
        tasks.value.splice(index, 1)
        total.value -= 1
      }

      // 如果是当前任务，清除当前任务
      if (currentTask.value?.id === taskId) {
        currentTask.value = null
      }
    } catch (error) {
      console.error('Failed to delete task:', error)
      throw error
    }
  }

  const retryTask = async (taskId: string) => {
    try {
      await request.post(`/videos/tasks/${taskId}/retry`)

      // 更新任务状态
      updateTask(taskId, {
        status: 'pending',
        progress: 0,
        current_step: '等待重新处理'
      })
    } catch (error) {
      console.error('Failed to retry task:', error)
      throw error
    }
  }

  const downloadVideo = async (taskId: string) => {
    try {
      const response = await request.get(`/videos/download/${taskId}`, {
        responseType: 'blob'
      })

      // 创建下载链接
      const blob = new Blob([response], { type: 'video/mp4' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url

      // 获取任务信息用于命名文件
      const task = tasks.value.find(t => t.id === taskId) || currentTask.value
      const filename = task?.title
        ? `${task.title}_${task.target_platform}.mp4`
        : `video_${taskId}.mp4`

      link.download = filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } catch (error) {
      console.error('Failed to download video:', error)
      throw error
    }
  }

  const clearTasks = () => {
    tasks.value = []
    currentTask.value = null
    total.value = 0
    currentPage.value = 1
  }

  // 分页方法
  const nextPage = async () => {
    if (currentPage.value * pageSize.value < total.value) {
      await fetchTasks({ page: currentPage.value + 1 })
    }
  }

  const prevPage = async () => {
    if (currentPage.value > 1) {
      await fetchTasks({ page: currentPage.value - 1 })
    }
  }

  const goToPage = async (page: number) => {
    if (page >= 1 && page <= Math.ceil(total.value / pageSize.value)) {
      await fetchTasks({ page })
    }
  }

  return {
    // 状态
    tasks,
    currentTask,
    loading,
    total,
    currentPage,
    pageSize,

    // 计算属性
    completedTasks,
    processingTasks,
    failedTasks,
    pendingTasks,

    // 方法
    fetchTasks,
    fetchTask,
    updateTask,
    deleteTask,
    retryTask,
    downloadVideo,
    clearTasks,
    nextPage,
    prevPage,
    goToPage
  }
})